package gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import main.Coord;
import main.PlayerStats;
import main.TDMap;
import towers.Tower;
import towers.TowerTemplate;

public class GuimapListener implements MouseListener, KeyListener {

	private TDMap map;
	private Guimap gui;
	private Selection selection;
	private PlayerStats ps;
	
	public GuimapListener(TDMap map, Guimap gui, Selection selection, PlayerStats ps) {
		this.ps = ps;
		this.selection = selection;
		this.map = map;
		this.gui = gui;
	}
	
	@Override
	public void mouseClicked(MouseEvent mouse) {
		int x = mouse.getX()/Guimap.TILE_WIDTH;
		int y = mouse.getY()/Guimap.TILE_HEIGHT;
		Coord cord = new Coord(x, y);
		
		if (x<Guimap.MAP_WIDTH && y < Guimap.MAP_HEIGHT) {
			boolean empty = true;
			Tower clicked=null;
			for (Entry<Coord, Tower> e: map.getTowerMap().entrySet()) {
				if (e.getKey().equals(cord)) {
					empty=false;
					clicked=e.getValue();
					break;
				}
			}
			
			if (empty) {
				if (selection.type() == Selection.BUY) {
					TowerTemplate tt = selection.getTemplate();
					if (ps.cash >= tt.cost) {
						Tower t = new Tower(tt);
						t.place(cord, map);
						map.addTower(cord, t);
						ps.cash -= tt.cost;
						ps.upd();
					}
				}
			} else {	// Not empty
				selection.set(clicked, Selection.TOWER);
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {}

	@Override
	public void mouseExited(MouseEvent arg0) {}

	@Override
	public void mousePressed(MouseEvent arg0) {}

	@Override
	public void mouseReleased(MouseEvent arg0) {}

	@Override
	public void keyPressed(KeyEvent key) {
		switch (key.getKeyCode()) {
		case ' ': // space
			break;
		case 222: // '
			List<Coord> p = new ArrayList<Coord>();
			p.add(new Coord(0, 0));
			p.add(new Coord(10, 8));
			p.add(new Coord(20, 5));
			break;
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {}

	@Override
	public void keyTyped(KeyEvent arg0) {}

}
